package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //查询地址是否为空
        Long userId = BaseContext.getCurrentId();
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.findByIdAndUserId(addressBookId, userId);
        if (addressBook==null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询购物车是否为空
        List<ShoppingCart> shoppingCart = shoppingCartMapper.findShoppingCartUserById(userId);
        if (shoppingCart==null || shoppingCart.size()==0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //封装订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(0);
        orders.setUserId(userId);
            //查询用户数据并封装
        User user = userMapper.findUserByUserId(userId);
        orders.setUserName(user.getName());
            //从地址簿获取地址
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());
        //添加订单
        orderMapper.save(orders);
        //封装订单详情
        List<OrderDetail> list = shoppingCart.stream().map(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailMapper.saveDetailList(list);
        //删除购物车
        shoppingCartMapper.deleteCart(userId);
        //封装要返回的订单信息
        return  OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 提交订单
     * @param
     * @return
     */
    /*@Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        //1.查询地址信息
        AddressBook addressBook = addressBookMapper.findByIdAndUserId(ordersSubmitDTO.getAddressBookId(), userId);
        //2.判断用户有没有填写地址
        if (addressBook == null) {
            //出错
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2.查询当前用户有没有在购物车加入数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findShoppingCartUserById(userId);
        //没数据
        if (shoppingCarts == null||shoppingCarts.size()==0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //3.存订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //绑定数据
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);


        //查询user表 获取微信用户名
        User userByOpenid = userMapper.findUserByUserId(userId);
        orders.setUserName(userByOpenid.getName());
        //查询地址簿,获取信息
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());

        //添加订单
        orderMapper.save(orders);

        //4.存订单详情
        //注意事项 => 订单详情的数据来自于购物车数据
        List<OrderDetail> orderDetailList = shoppingCarts.stream()
                .map(shoppingCart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart,orderDetail);
                    orderDetail.setId(null); //这里一定要注意id的问题!!!
                    //设置订单id
                    orderDetail.setOrderId(orders.getId());
                    return orderDetail;
                })
                .collect(Collectors.toList());
        orderDetailMapper.saveDetailList(orderDetailList);

        //5.删除购物车
        shoppingCartMapper.deleteCart(userId);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCartMapper.delShoppingCart(shoppingCart);

        //6.组装数据返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

    }*/






    //订单结账,修改订单
    @Override
    public void update(String orderNum) {
        //1.根据订单号查询订单
        Orders orders = orderMapper.findOrderByOrderNum(orderNum);
        if(orders == null){
            //抛出异常 订单出问题
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.修改状态
        orders.setStatus(Orders.TO_BE_CONFIRMED); //待接单
        orders.setCheckoutTime(LocalDateTime.now()); //结账时间
        orders.setPayStatus(Orders.PAID);
        orderMapper.update(orders);
    }
}
